package com.example.observertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MapActivity extends AppCompatActivity {

    private TextView tv;
    private List<String> strs;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        tv = (TextView) findViewById(R.id.tv);
        getUserData();
        flatMap();
    }

    private List<String> getUserData(){
        strs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            strs.add("测试"+i);
        }
        return strs;
    }

    //map用法
    private void map(){
        Observable observable = Observable.just(1);

        observable.map(new Function<Integer,String>() {
            @Override
            public String apply(Integer integer) throws Exception {

                return integer+"";
            }
        });
    }

    private void flatMap(){
        Observable
                .just(strs)
                .map(new Function<List<String>, List<Integer>>() {
                    @Override
                    public List<Integer> apply(List<String> strings) throws Exception {
                        List<Integer> ints = new ArrayList<>();
                        for (int i = 0; i < strings.size(); i++) {
                            ints.add(i);
                        }
                        return ints;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<Integer>>() {
                    @Override
                    public void accept(List<Integer> integers) throws Exception {
                        tv.append(integers+"");
                    }
                });
    }

}
